package com.zygh.policeasset.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.policeasset.component.CommonResult;
import com.zygh.policeasset.mapper.VersionManagementMapper;
import com.zygh.policeasset.pojo.AppVersionUploadFile;
import com.zygh.policeasset.pojo.VersionManagement;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class VersionManagementService {
    @Autowired
    VersionManagementMapper versionManagementMapper;

    @Value("${app.upload}")
    String FjFile;

    public VersionManagement queryById(Integer id) {
        return this.versionManagementMapper.queryById(id);
    }

    public PageInfo queryAll(int pageNum, int pageSize, VersionManagement versionManagement) {
        PageHelper.startPage(pageNum, pageSize);
        List<VersionManagement> list = this.versionManagementMapper.queryAll(versionManagement);
        return new PageInfo(list);
    }

    public CommonResult insert(VersionManagement versionManagement) {
        int res = this.versionManagementMapper.queryByEditionNum(versionManagement.getEditionNum()).intValue();
        if (res > 0){
            return (new CommonResult()).validateFailed("版本号已存在");
        }

       versionManagement.setEditionNum(Integer.valueOf(this.versionManagementMapper.queryMaxEditionNum().intValue() + 1));
        versionManagement.setCreateTime(DateUtil.now());
        int count = this.versionManagementMapper.insert(versionManagement);
        if (count > 0)
            return (new CommonResult()).success();
        return (new CommonResult()).validateFailed("添加失败");
    }

    public CommonResult update(VersionManagement versionManagement) {
        int count = this.versionManagementMapper.update(versionManagement);
        if (count > 0)
            return (new CommonResult()).success();
        return (new CommonResult()).validateFailed("修改失败");
    }

    public CommonResult deleteById(Integer id) {
        int count = this.versionManagementMapper.deleteById(id);
        if (count > 0)
            return (new CommonResult()).success();
        return (new CommonResult()).validateFailed("删除失败");
    }

    public CommonResult checkVersion(Integer editionNum) {
        HashMap<Object, Object> map = new HashMap<>(16);
        try {
            VersionManagement versionManagement = this.versionManagementMapper.queryByIdDesc();
            if (!StringUtils.isEmpty(versionManagement)) {
                if (editionNum.intValue() >= versionManagement.getEditionNum().intValue()) {
                    map.put("status", Boolean.valueOf(true));
                    map.put("url", "");
                    map.put("name", "");
                    return (new CommonResult()).success(map);
                }
                map.put("status", Boolean.valueOf(false));
                map.put("url", versionManagement.getUrl());
                map.put("name", versionManagement.getEdition());
                return (new CommonResult()).success(map);
            }
            return (new CommonResult()).validateFailed("未发布新版本APP");
        } catch (Exception e) {
            return (new CommonResult()).validateFailed(e.toString());
        }
    }

    public CommonResult uploadFile(AppVersionUploadFile appVersionUploadFile) {
        String url = null;
        String filename = null;
        MultipartFile file = appVersionUploadFile.getFile();
        if (file == null || "".equals(file) || file.getSize() == 0L) {
            return (new CommonResult()).validateFailed("文件不符合要求");
        }
        String filePath = this.FjFile;
        String str = DateUtil.now().replaceAll("[[\\s-:punct:]]", "");
        try {
            File path = new File(filePath);
            if (!path.getParentFile().exists())
                path.mkdirs();
            InputStream in = null;
            try {
                in = file.getInputStream();
                filename = str + file.getOriginalFilename();
                filePath = filePath + "" + filename;
                File newfile = new File(filePath);
                FileUtils.copyInputStreamToFile(in, newfile);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null)
                        in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            url = "/downLoadApp/" + filename;
        } catch (Exception e) {
            e.printStackTrace();
        }
        int res = this.versionManagementMapper.update((new VersionManagement())
                .setId(Integer.valueOf(appVersionUploadFile.getId()))
                .setReleaseStatus(Integer.valueOf(1))
                .setUrl(url));
        if (res > 0)
            return (new CommonResult()).success(filePath);
        return (new CommonResult()).validateFailed("上传错误");
    }

    public CommonResult remove(Integer id, String url) {
        if (StrUtil.isEmpty(String.valueOf(id))) {
            return (new CommonResult()).validateFailed("id不能为空");
        }
        String str = url.split("download/")[1];
        String fileUrl = this.FjFile + "/" + str;
        File file = new File(fileUrl);
        if (!file.exists()) {
            System.out.println("文件不存在");
        } else {
            file.delete();
        }
        int res = this.versionManagementMapper.updateUrl((new VersionManagement())
                .setId(id)
                .setReleaseStatus(Integer.valueOf(0))
                .setUrl(null));
        if (res > 0)
            return (new CommonResult()).success();
        return (new CommonResult()).validateFailed("删除失败");
    }
}
